

module sync_cycle_detect(
	input			clk,		
	input			rst_n,	
	input			P20_SYNC,
    input           TEMP_SEL,	
    input   [15:0]  pulse_width,				
	output			RFA_out				
);
/************************************/
localparam	FREQ_MIN    = 16'd3610; //27.7K
localparam	FREQ_MAX    = 16'd1600; //62.5k 
localparam	FREQ_35K    = 16'd2816; //35.5k
/************************************/
reg         sync_r0,sync_r1,sync_r2;
reg         temp_r0,temp_r1,temp_r2;
reg [15:0]  sync_cnt;
reg [15:0]  ttl_cycle;
reg [15:0]  ttl_cnt;
reg [15:0]  ttl_high;
reg         ttl_out;

assign RFA_out = ttl_out;

/******************sync cnt******************/
always @(posedge clk or negedge rst_n)begin 
    if(!rst_n)begin	
		sync_r0 <= 1'b0;
		sync_r1 <= 1'b0;
        sync_r2 <= 1'b0;

        temp_r0 <= 1'b0;
        temp_r1 <= 1'b0;
        temp_r2 <= 1'b0;
	end	
    else begin
		sync_r0 <= P20_SYNC;
		sync_r1 <= sync_r0;
        sync_r2 <= sync_r1;

        temp_r0 <= TEMP_SEL;
        temp_r1 <= temp_r0;
        temp_r2 <= temp_r1;
	end
end

always @(posedge clk or negedge rst_n)begin 
	if(!rst_n)
		sync_cnt <= 16'd0;	
	else if(sync_r1 == 1'b1 && sync_r2 == 1'b0)
		sync_cnt <= 16'd0;
    else if(sync_cnt < FREQ_MIN)
        sync_cnt <= sync_cnt + 1'd1;
    else
        sync_cnt <= sync_cnt;
end

/******************RFA OUT******************/
always @(posedge clk or negedge rst_n)begin 
	if(!rst_n)
		ttl_cycle <= 16'd0;	
	else if(sync_r1 == 1'b1 && sync_r2 == 1'b0)begin
        if(sync_cnt < FREQ_MAX)
            ttl_cycle <= FREQ_MAX;
        else 
            ttl_cycle <= sync_cnt;
    end
    else
        ttl_cycle <= ttl_cycle;
end

always @(posedge clk or negedge rst_n)begin 
	if(!rst_n)
		ttl_high <= 16'd300;
    else
        ttl_high <= (pulse_width << 4) - (pulse_width >> 2) - (pulse_width >> 1);
end

always @(posedge clk or negedge rst_n)begin 
	if(!rst_n)
		ttl_cnt <= 16'd0;	
	else if(ttl_cnt >= ttl_cycle)
		ttl_cnt <= 16'd0;	
	else
		ttl_cnt <= ttl_cnt + 1'd1;
end

always @(posedge clk or negedge rst_n)begin 
	if(!rst_n)
		ttl_out <= 1'b0;
    else if(ttl_cycle < FREQ_35K)        //>35K
        ttl_out <= ttl_cnt < 16'd300;   //3us
    else if(temp_r2)
        ttl_out <= ttl_cnt < 16'd1200;  //12us	
	else
		ttl_out <= ttl_cnt < 16'd1200;  //12us						
end	

endmodule

